package com.yidingdui.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yidingdui.domain.entity.ModelHistory;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface ModelHistoryMapper extends BaseMapper<ModelHistory> {
    
    @Insert("INSERT INTO model_history (task_id, user_id, prompt, image_file_name, enable_pbr, result_format, status, result_url, error_message, created_at, updated_at) " +
            "VALUES (#{taskId}, #{userId}, #{prompt}, #{imageFileName}, #{enablePBR}, #{resultFormat}, #{status}, #{resultUrl}, #{errorMessage}, #{createdAt}, #{updatedAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertModelHistory(ModelHistory modelHistory);
    
    @Select("SELECT id, task_id AS taskId, user_id AS userId, prompt, image_file_name AS imageFileName, " +
            "enable_pbr AS enablePBR, result_format AS resultFormat, status, result_url AS resultUrl, " +
            "error_message AS errorMessage, created_at AS createdAt, updated_at AS updatedAt, completed_at AS completedAt " +
            "FROM model_history WHERE task_id = #{taskId}")
    ModelHistory findByTaskId(String taskId);
    
    @Select("SELECT id, task_id AS taskId, user_id AS userId, prompt, image_file_name AS imageFileName, " +
            "enable_pbr AS enablePBR, result_format AS resultFormat, status, result_url AS resultUrl, " +
            "error_message AS errorMessage, created_at AS createdAt, updated_at AS updatedAt, completed_at AS completedAt " +
            "FROM model_history WHERE user_id = #{userId} ORDER BY created_at DESC")
    List<ModelHistory> findByUserId(Long userId);
    
    @Update("UPDATE model_history SET status = #{status}, result_url = #{resultUrl}, error_message = #{errorMessage}, updated_at = #{updatedAt}, completed_at = #{completedAt} WHERE task_id = #{taskId}")
    int updateByTaskId(ModelHistory modelHistory);
    
    @Select("SELECT id, task_id AS taskId, user_id AS userId, prompt, image_file_name AS imageFileName, " +
            "enable_pbr AS enablePBR, result_format AS resultFormat, status, result_url AS resultUrl, " +
            "error_message AS errorMessage, created_at AS createdAt, updated_at AS updatedAt, completed_at AS completedAt " +
            "FROM model_history WHERE user_id = #{userId} AND created_at >= #{startTime} ORDER BY created_at DESC")
    List<ModelHistory> findByUserIdAndTimeRange(@Param("userId") Long userId, @Param("startTime") LocalDateTime startTime);
}
